<template>
  <!-- 编辑弹窗 -->
  <el-dialog
    @opened="openDialog" 
    :width="dialogWidth"  
    :title="title" 
    :visible.sync="showEditDialog"  
    :show-close="false"  
    :close-on-click-modal="false"  
  >
    <el-form 
      :model="forms"  
      :rules="rules"  
      ref="editForms"  
      class="edit-forms"  
      label-position="left"  
      :label-width="labelWidth" 
    >
      <el-form-item label="图片" prop="imgUrl">  <!-- 表单项 -->
        <el-upload  
          name="file"  
          class="avatar-uploader"  
          :action="serverApiUrl + '/file/addFile'"  
          :show-file-list="false"  
          :on-success="handleAvatarSuccess"  
          :before-upload="beforeAvatarUpload"  
        >
          <img v-if="forms.url" :src="forms.url" class="avatar" />  <!-- 已上传图片的预览 -->
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>  <!-- 上传按钮图标 -->
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">  <!-- 弹窗底部 -->
      <el-button @click="$emit('close')">取 消</el-button>  <!-- 取消按钮 -->
      <el-button type="primary" @click="submit">确认</el-button>  <!-- 确认按钮 -->
    </div>
  </el-dialog>
</template>

<script>
import {
  Required,
  Float2,
  Boolean,
  FillerFieldRules
} from "@/utils/validateRules";  // 引入表单验证规则
import { serverApiUrl } from "@/config/apiUrl";  // 引入接口地址配置
import { fillerLeft, resetObject } from "@/utils/common"; //引入通用工具方法 
import { saveOrUpdateBanner, getBannerById } from "@/api/bannerManage/list";  //引入保存或更新横幅、通过ID获取横幅的接口方法
export default {
  props: {
    title: {
      type: String,
      default: "编辑"
    },
    dialogWidth: {
      type: String,
      default: "700px"
    },
    labelWidth: {
      type: String,
      default: "120px"
    },
    showEditDialog: Boolean
  },
  data() {
    return {
      forms: {
        name: "",
        url: "",  // 预览图片的完整路径 -->
        imgUrl: "",  //保存到数据库的图片名称
      },
      rules: {
        ...FillerFieldRules(["name"], Required),  //表单字段name的必填验证规则
        price: [Required, Float2],  //表单字段price的必填、最多保留两位小数的验证规则
        categoryid: Boolean  //表单字段categoryid的布尔值验证规则
      },
      serverApiUrl: serverApiUrl,  //提供给模板中使用的接口地址配置

    };
  },

  methods: {

    submit() {
      this.$refs.editForms.validate(valid => {
        if (valid) {
          // 表单验证通过
          this.$message({
            message: "字段验证通过，提交请求，成功后刷新分页！",
            type: "success"
          });
          saveOrUpdateBanner(this.forms)
            .then(r => {
              this.$message({
                message: r.msg,
                type: "success"
              });
              this.$emit("success");
              this.$parent.showEditDialog = false;
            })
            .catch(() => { });
        } else {
          // 表单验证未通过
          this.$message({
            message: "请按照提示正确填写内容！",
            type: "warning"
          });
          return false;
        }
      });
    },
    openDialog() {
      if (this.$parent.id != null) {
        // 编辑
        getBannerById({ id: this.$parent.id })
          .then(r => {
            // 根据id获取轮播图信息
            this.FillerFormField(this.$parent.id, r);
            this.forms.url = this.$parent.serverImageUrl + r.imgUrl;
            this.$parent.id = null;
          })
          .catch(() => { });
      } else {
        // 新增
        resetObject(this.forms);
        this.$set(this.forms, "id", null);
        this.$refs.editForms.resetFields();
      }
    },
    FillerFormField(id, data) {
      // 可以外部填充回写做编辑用，也可以请求详情接口填充表单
      this.$set(this.forms, "id", id);
      fillerLeft(this.forms, data);
    },
    handleAvatarSuccess(res, file) {
      this.$message({
        type: "info",
        message: "图片上传成功",
        duration: 6000
      });
      if (file.status == "success") {
        this.forms.imgUrl = res.fileUrl;
        this.forms.url = URL.createObjectURL(file.raw);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    }
  }
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>